package com.utilus.usart;


import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import org.springframework.stereotype.Service;

import java.util.List;
import static com.MysqlApplication.global_data;


@Service
public final class Usart {


    public  void usart_init( ) throws Exception {



            List<String> serialPortList = SerialPortUtils.getSerialPortList();
            for (String s : serialPortList) {
                System.out.println(s);
            }

            final   SerialPort  serialPort= SerialPortUtils.openSerialPort("COM3");


        // 启动一个线程每2s向串口发送数据，发送1000次hello
        new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 1;
                while (i < 1000) {
                    String s = "hello";
                    s+=global_data.getLog_Grade();
                    byte[] bytes = s.getBytes();
                    SerialPortUtils.sendData(serialPort, bytes);// 发送数据
                    i++;
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();



        // 设置串口的listener
        SerialPortUtils.setListenerToSerialPort(serialPort, new SerialPortEventListener() {
            @Override
            public void serialEvent(SerialPortEvent arg0) {

                if (arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE) {// 数据通知
                    byte[] bytes = SerialPortUtils.readData(serialPort);
                    System.out.println("收到的数据长度：" + bytes.length);
                    System.out.println("收到的数据：" + new String(bytes));
                }
            }
        });
        // closeSerialPort(serialPort);
    }
}